<?php
set_time_limit(0);
$root=preg_replace('/cron$/', '', dirname(__FILE__));

require_once($root."inc.config.php");
require_once($root."functions/common/common.php");
require_once($root."functions/general_function.php");
require_once($root."functions/search/search_function.php");
require_once($root."initialize.php");

if(1){
	if(($db_msg=cron_initialize()) !== true){
		$errmsg="Error starting Automatic Withdrawal due to database error.<br />\n<br />\n$db_msg";
		$a_sub="$vars[title] - Automatic Withdrawal Failed";
		$a_msg=
		"<p>Dear admin,</p>
		$errmsg";
		email_admin($a_sub, $a_msg, 'e');
	}else{
		$db=$vars["db"];
		$comm_time = mktime(0,0,0,ndate('n'),ndate('j')-1,ndate('Y'));
		$comm_date = date('Y-m-d H:i:s', $comm_time);
		$year = date('Y', $comm_time);
		$month = date('n', $comm_time);
		$day = date('j', $comm_time);

		//####################automatic withdrawal####################
		$comm_title = "Automatic Withdrawal";
		$comm_code = "w";
		$comm_date_d=date('j - M - Y', $comm_time);

		//executed = check cron_table if exist with type = member rank, week, month, year
		if(!($r=mysql_query("select count(*) from $db->cron where type='$comm_code' and year='$year' and month='$month' and day='$day'"))){
			$errmsg[$comm_code]="Error starting $comm_title [$comm_date_d] due to database error.<br />\n<br />\n".mysql_error();
		}else{
			if(($executed[$comm_code] = @mysql_result($r, 0)) === false){
				$errmsg[$comm_code]="Error starting $comm_title [$comm_date_d] due to database error.<br />\n<br />\n".mysql_error();
			}
		}

		if(!$errmsg[$comm_code]){
			if (!$executed[$comm_code]){
				//insert into cron_table type = automatic withdrawal, started = y, year, month, day, cron start date = datetime
				$sql = "insert into $db->cron (type, started, completed, success, year, month, day) values ('$comm_code', '".ndate($vars["system_date_format"])."', 'n', 'n', '$year', '$month', '$day')";
				if(!mysql_query($sql)){
					$errmsg[$comm_code].="Error starting $comm_title [comm_date_d] due to database error.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
				}else{
					//cron_id = last insert id
					$cron_id = mysql_insert_id();
					$result = auto_withdraw($comm_date);
					$comm_errmsg_d = '';
					if($result['status'] === true){
						$success = 'y';
						$executed[$comm_code] = true;
					}else{
						$errmsg[$comm_code] = "$comm_title [$comm_date_d] completed with errors:<br />\n<br />\n".$result['errmsg'];
						$success = 'n';
					}
					if($result['errmsg']){
						$comm_errmsg = $result['errmsg'];
						$comm_errmsg_d = mysql_real_escape_string($result['errmsg']);
					}
					$sql = "update $db->cron set completed='y', success='$success', ended='".ndate($vars["system_date_format"])."', message='$comm_errmsg_d' where id='$cron_id'";
					if(!mysql_query($sql)){
						$errmsg[$comm_code]="Error completing the $comm_title [$comm_date_d] due to database error.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n".($errmsg[$comm_code]? "<br />\n".$errmsg[$comm_code] : "");
					}
				}
			}
		}
		if ($errmsg[$comm_code]){
			$a_sub="$vars[title] - $comm_title [$comm_date_d] with Error";
			$a_msg=
			"<p>Dear admin,</p>
			".$errmsg[$comm_code];
			email_admin($a_sub, $a_msg, 'e');
		}
	}
}

function auto_withdraw($in_date){
	global $vars;
	$db=$vars["db"];

	$settings=get_settings("member_withdraw_min");
	$datetime=ndate($vars["system_date_format"]);

	$wit_date = date('Y-m-d', strtotime($in_date));
	$wit_date_time = $wit_date.' 23:59:59';
	if($t=@mysql_num_rows($r=mysql_query("select id from $db->users where ewallet>".($settings['member_withdraw_min'])))){
		$wi = 0;
		for($i=0;$i<$t;$i++){
			$user=mysql_fetch_assoc($r);
			$user = get_user_detail_by_id($user['id']);
			if($user["bank_name"]=="" || $user["name"]=="" || $user["bank_acc_no"]==""){
				$incomplete[]=$user;
			}elseif(0){//!in_array($user['bank_name'], $vars['dbv']['bank'])){
				$incomplete[]=$user;
			}elseif(strlen($user['bank_acc_no']) < 8){//$vars['dbv']['bank_length'][$user['bank_name']] && strlen($user['bank_acc_no']) != $vars['dbv']['bank_length'][$user['bank_name']]){
				$incomplete[]=$user;
			}else{
				$success=false;
				//deduct member e-wallet
				$deduct_amount = $user['ewallet'];
				if(false){//!mysql_query($sql="update $db->users set ewallet=ewallet-$deduct_amount where id='$user[id]' limit 1")){
					$deduct_err.="SQL: $sql<br />\nError: ".mysql_error()."<br />\n";
				}else{
					//create withdrawal
					$refno = '';
					$actual_amount = $deduct_amount;
					if(!mysql_query($sql="insert into $db->member_withdraw (uid, amount, payment_type, acc_name, acc_payee_name, acc_no, remark, autowit, status, cdate) values ('$user[id]', '$actual_amount', 'o', '".mysql_real_escape_string($user['bank_name'])."', '".mysql_real_escape_string($user['name'])."', '".mysql_real_escape_string($user['bank_acc_no'])."', '".mysql_real_escape_string("Automatic Withdrawal ($wit_date)")."', 'y', 'pending', '$wit_date_time')")){
						$wit_err.="SQL: $sql\nError: ".mysql_error()."\n";
						$new_wid="Error";
					}else{
						$success=true;
						$new_wid=mysql_insert_id();
						$refno = $new_wid;
					}
					//create ewallet record
					if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr ,cdate) values ('$user[id]', 'd', '$actual_amount', '".mysql_real_escape_string("System Automatic Withdrawal ($wit_date) Ref #$refno")."', '$wit_date_time')")){
						$ewr_err.="SQL: $sql\nError: ".mysql_error()."\n";
					}else{
						$new_eid = mysql_insert_id();
						$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$user[id]' and id!=$new_eid order by id desc limit 1"), 0);
						if(!$last_bal){
							$last_bal = 0;
						}
						$last_bal -= $actual_amount;
						@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
					}
					//withdrawal charge
					if($settings['auto_withdraw_charge'] > 0){
						if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr ,cdate) values ('$user[id]', 'd', '$settings[auto_withdraw_charge]', '".mysql_real_escape_string("System Automatic Withdrawal charge ($wit_date) Ref #$refno")."', '$wit_date_time')")){
							$ewr_err.="SQL: $sql\nError: ".mysql_error()."\n";
						}else{
							$new_eid = mysql_insert_id();
							$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$user[id]' and id!=$new_eid order by id desc limit 1"), 0);
							if(!$last_bal){
								$last_bal = 0;
							}
							$last_bal -= $settings['auto_withdraw_charge'];
							@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
						}
					}
				}
				//email user later
				if($success){
					$completed[$wi]=$user;
					$completed[$wi]['amount']=$actual_amount;
					$completed[$wi]['refno']=$refno;
					$wi++;
				}
			}
		}

		//email admin
		if($t=count($completed)){
			for($i=0;$i<$t;$i++){
				$success_wit.="User ID: ".$completed[$i]["id"]." Amount: ".number_format($completed[$i]["amount"], 2)."<br />\n";
			}
			$a_sub="$vars[ewallet_title] Automatic Withdrawal for $wit_date";
			$a_msg=
			"<p>Dear admin,</p>
			<p>$vars[ewallet_title] Automatic Withdrawal for $wit_date:</p>
			<p>$success_wit</p>
			<p>You can view all this withdrawal in the administrative panel and process the withdrawal from there.</p>";
			email_admin($a_sub, $a_msg);
		}
		//error msg to admin
		if($deduct_err || $wit_err || $ewr_err){
			$a_sub="Error $vars[ewallet_title] Automatic Withdrawal for $wit_date";
			$a_msg="<p>Dear admin,</p>
			<p>The system had encountered some error(s) while performing the automatic withdrawal:</p>".
			($deduct_err?
			"<p>Error deducting the members $vars[ewallet_title] account as below, no action is necessary for this error. However if this error occurs frequently please contact us:<br />\n<br />\n".nl2br($deduct_err)."</p>" : "").
			($wit_err? "
			<p>Error creating the withdrawal record but the member has already deducted with the withdrawal amount. The solution is to execute the below SQL to properly create the withdrawal record:<br />\n<br />\n".nl2br($wit_err)."</p>" : "").
			($ewr_err? "
			<p>Error creating the $vars[ewallet_title] transaction record. The solution is to execute the below SQL to properly create the $vars[ewallet_title] transaction record:<br />\n<br />\n".nl2br($ewr_err)."</p>" : "");
			email_admin($a_sub, $a_msg, 'e');
		}

		//error message email user
		if($t=count($incomplete)){
			$u_sub="Automatic Withdrawal Unsuccessful";
			$u_msg=
			"<p>Dear <%name%> (<%id%>),</p>
			<p>We are sorry that we cannot process the Automatic Withdrawal for your account since your payment information is incomplete. However you can manually 
			request for withdrawal from the <%title%> member area.</p>
			<p><%ewallet%> Account Balance: <%currency%> <%x%></p>";
			for($i=0;$i<$t;$i++){
				$user = $incomplete[$i];
				if($user['email']){
					$u_msg2=replace_tag($u_msg, array("<%ewallet%>"=>$vars["ewallet_title"], "<%name%>"=>$user["name"], "<%id%>"=>$user["id"], "<%title%>"=>$vars["title"], "<%currency%>"=>$vars["currency"], "<%x%>"=>number_format($user["ewallet"], 2)));
					email_user($user["email"], $u_sub, $u_msg2);
				}
			}
		}
		//email user
		if($t=count($completed)){
			$u_sub="$vars[ewallet_title] Automatic Withdrawal for $wit_date";
			$u_msg=
			"<p>Dear <%name%> (ID#<%id%>),</p>
			<p>The system had automatically submitted an Automatic <%ewallet%> Withdrawal for your account for $wit_date:</p>
			<p>Withdrawal Ref #: <span style='color:red; font-weight:bold;'><%refno%></span><br />
			Withdrawal Amount: <%currency%><%amount%><br />
			Bank: <%bank%><br />
			Payee Name: <%payee_name%><br />
			Bank Account Number: <%acc_no%></p>
			<p>You can view the withdrawal details in your <%title%> member area.</p>";
			for($i=0;$i<$t;$i++){
				$user = $completed[$i];
				if($user['email']){
					$u_msg2=replace_tag($u_msg, array(
					"<%ewallet%>"=>$vars["ewallet_title"],
					"<%name%>"=>$user["name"],
					"<%id%>"=>$user["id"],
					"<%title%>"=>$vars["title"],
					"<%currency%>"=>$vars["currency"],
					"<%refno%>"=>strval($user["refno"]),
					"<%amount%>"=>number_format($user['amount'], 2),
					"<%charge%>"=>number_format($settings['auto_withdraw_charge'], 2),
					"<%total%>"=>number_format($user['amount'] + $settings['auto_withdraw_charge'], 2),
					"<%bank%>"=>$user['bank_name'],
					"<%payee_name%>"=>$user['name'],
					"<%acc_no%>"=>$user['bank_acc_no']));
					email_user($user['email'], $u_sub, $u_msg2);
				}
			}
		}
	}
	
	//format all error message
	if($deduct_err || $wit_err || $ewr_err){
		$errmsg="The system had encountered some error(s) while performing the automatic withdrawal:\n".
		($deduct_err? "\nError deducting the members $vars[ewallet_title] account as below, no action is necessary for this error. However if this error occurs frequently please contact us:\n\n$deduct_err\n" : "").
		($wit_err? "\nError creating the withdrawal record but the member has already deducted with the withdrawal amount. The solution is to execute the below SQL to properly create the withdrawal record:\n\n$wit_err\n" : "").
		($ewr_err? "\nError creating the $vars[ewallet_title] transaction record. The solution is to execute the below SQL to properly create the $vars[ewallet_title] transaction record:\n\n$ewr_err\n" : "");
		$result['status'] = false;
		$result['errmsg'] = $errmsg;
	}else{
		$result['status'] = true;
	}
	
	return $result;
}
?>